package com.wch.swh;

import java.util.ArrayList;
import java.util.Random;

import com.wch.swh.MainActivity4.ButtonHandler;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

	private final int BUTTON_1 = 0;          
	private final int BUTTON_2 = 1;
	private final int BUTTON_3 = 2;
	private final int BUTTON_4 = 3;
	private final int YOUR_TURN = 4;
	private final int NEW_GAME_ID = 100; 
	
	private TextView   score_board;    
	private TextView   level_board;    
	private TextView   next_turn;      
	private ImageView  btn1;          
	private ImageView  btn2;
	private ImageView  btn3;
	private ImageView  btn4;
	private Button     startBtn;
	
	private ButtonHandler mHandler;
	private Handler handler = new Handler();
	                                  
	private int level_count = 1;
	private int score = 0;
	private ArrayList<Integer> saveOrderOfCom = new ArrayList<Integer>();  
	private ArrayList<Integer> saveOrderOfUsr = new ArrayList<Integer>();  
	                                                                        
	                                                                       
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        initLayout();
        initScore();
    }
    
    public void initLayout()
    {
    	score_board = (TextView) findViewById(R.id.score);
    	level_board = (TextView) findViewById(R.id.level_count);
    	next_turn   = (TextView)findViewById(R.id.text);
    	
    	btn1 = (ImageView)findViewById(R.id.btn1);
    	btn2 = (ImageView)findViewById(R.id.btn2);
    	btn3 = (ImageView)findViewById(R.id.btn3);
    	btn4 = (ImageView)findViewById(R.id.btn4);
    	
    	btn1.setOnTouchListener(new View.OnTouchListener(){
			@Override
			public boolean onTouch(View arg0, MotionEvent motion) {
				switch(motion.getAction())
				{
					case MotionEvent.ACTION_UP:
						compare(BUTTON_1);
						break;
				}
				return false;
			}
    		
    	});
    	
    	btn2.setOnTouchListener(new View.OnTouchListener(){
			@Override
			public boolean onTouch(View arg0, MotionEvent motion) {
				switch(motion.getAction())
				{
					case MotionEvent.ACTION_UP:
						compare(BUTTON_2);
						break;
				}
				return false;
			}
    		
    	});
    	
    	btn3.setOnTouchListener(new View.OnTouchListener(){
			@Override
			public boolean onTouch(View arg0, MotionEvent motion) {
				switch(motion.getAction())
				{
					case MotionEvent.ACTION_UP:
						compare(BUTTON_3);
						break;
				}
				return false;
			}
    		
    	});
    	
    	btn4.setOnTouchListener(new View.OnTouchListener(){
			@Override
			public boolean onTouch(View arg0, MotionEvent motion) {
				switch(motion.getAction())
				{
					case MotionEvent.ACTION_UP:
						compare(BUTTON_4);
						break;
				}
				return false;
			}
    		
    	});
    	
    	startBtn = (Button)findViewById(R.id.startbtn);
    	startBtn.setOnClickListener(new View.OnClickListener() {
			
			@SuppressLint("NewApi")
			@Override
			public void onClick(View arg0) {
				settingOrder();   
				if(saveOrderOfCom != null && saveOrderOfCom.size() > 0)
				{
					startBtn.setVisibility(View.INVISIBLE);   
					doitRunOnUiThread();   
					
					invalidateOptionsMenu();
				}
				
			}
		});
    }
    
    @SuppressLint("NewApi")
	private void initScore()
    {
    	level_count = 1;
    	score = 0;
    	score_board.setText(score+"");
    	level_board.setText(level_count+"");
    	next_turn.setText("");
    	
    	saveOrderOfCom.clear();
    	saveOrderOfUsr.clear();
    	
    	startBtn.setVisibility(View.VISIBLE);
    	setButtonEnable(false);
    	
    	invalidateOptionsMenu();
    }

    private void setButtonEnable(boolean val)
    {
    	btn1.setEnabled(val);
		btn2.setEnabled(val);
		btn3.setEnabled(val);
		btn4.setEnabled(val);
    }
    
    private void compare(int btn)
    {
    	if(saveOrderOfUsr.get(0) == btn)
		{
			score += 20;
			score_board.setText(score+"");
			saveOrderOfUsr.remove(0);   

			if(saveOrderOfUsr != null && saveOrderOfUsr.size() == 0)
			{
				level_count++;
				level_board.setText(level_count+"");
				
				settingOrder();  
				
				if(saveOrderOfCom != null && saveOrderOfCom.size() > 0)
				{
					doitRunOnUiThread();  
				}
			}
		}
		else   
		{
			new AlertDialog.Builder(this)
			.setTitle("Level " + (level_count - 1))
			.setMessage("Your Score is "+ score +".")
			.setCancelable(false)
			.setPositiveButton("Yes",new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					initScore();  
				}
			}).show();
		}
    }
    
    private void settingOrder()
    {
    	Random random = new Random();
    	for(int i=0; i < level_count; i++)
    	{
    		int num = random.nextInt(3);
    		saveOrderOfCom.add(i,num);
    		saveOrderOfUsr.add(i,num);
    	}
    }
    
    public void ButtonClickShow()
    {
    	switch(saveOrderOfCom.get(0))
    	{
	    	case BUTTON_1:
	    		btn1.setPressed(true);
	    		break;
	    	case BUTTON_2:
	    		btn2.setPressed(true);
	    		break;
	    	case BUTTON_3:
	    		btn3.setPressed(true);
	    		break;
	    	case BUTTON_4:
	    		btn4.setPressed(true);
	    		break;
    	}
    	
    	saveOrderOfCom.remove(0);  
    	handler.postDelayed(run,300);
    }
    
    Runnable run = new Runnable()
    {
		@Override
		public void run() {
			btn1.setPressed(false);
			btn2.setPressed(false);
			btn3.setPressed(false);
			btn4.setPressed(false);
		}
    };
    
    private void doitRunOnUiThread()
    {
    	next_turn.setText(R.string.computer_turn);
    	setButtonEnable(false);  
    	
    	if(mHandler == null)
    	{
    		mHandler = new ButtonHandler();	
    	}
    	
    	new Thread()
    	{
			@Override
			public void run() {
				for(int i = 0; i<level_count; i++)
				{
					try
					{
						runOnUiThread(new Runnable(){
							@Override
							public void run() {
								ButtonClickShow();
							}
						});
						Thread.sleep(600);
					}catch(InterruptedException e)
					{
						e.printStackTrace();
					}
				}
				
				Message msg = mHandler.obtainMessage(YOUR_TURN);
				mHandler.sendMessage(msg);
			}
    	}.start();
    }
    
    class ButtonHandler extends Handler{

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			switch(msg.what)
			{
				case YOUR_TURN:
					setButtonEnable(true);
					next_turn.setText(R.string.your_turn);
					break;
			}
		}
    }

    
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		
		menu.clear();
		if(startBtn.getVisibility() == View.INVISIBLE)
		{
			menu.add(0, NEW_GAME_ID, 0 ,R.string.new_game);
		}
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId())
		{
			case NEW_GAME_ID:
				initScore();
				break;
		}
		return true;
	}

	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		switch(keyCode)
		{
		 	case KeyEvent.KEYCODE_BACK:
		 		new AlertDialog.Builder(this)
				.setTitle("Finish")
				.setMessage("Do you want to finish?")
				.setCancelable(false)
				.setPositiveButton("Yes",new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						finish();
					}
				})
				.setNegativeButton("No",new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{

					}
				}).show();
			break;
		}
		
		return super.onKeyDown(keyCode, event);
	}

	
	@Override
	protected void onDestroy() {
		super.onDestroy();

		saveOrderOfCom = null;
		saveOrderOfUsr = null;
	}
}
